package com.ysyc.driver_ee.tools;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import com.ysyc.driver_ee.R;
import com.ysyc.driver_ee.base.GlobeContext;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/25.
 */

public class PermissionUtils {
    private static AlertDialog dialog;

    public interface PermissionGrant {
        void onPermissionGranted(int requestCode);
    }

    /**
     * Requests permission.
     *
     * @param activity
     */
    public static void requestPermissions(final Activity activity, final int requestCode, final String[] requestPermissions, PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }

        ArrayList<String> noGrantedList = new ArrayList<>();
        for (int i = 0; i < requestPermissions.length; i++) {
            int checkSelfPermission = -1;
            try {
                checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermissions[i]);
                if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                    noGrantedList.add(requestPermissions[i]);
                }

            } catch (RuntimeException e) {
                Toast.makeText(activity, activity.getString(R.string.please_open_the_appropriate_permissions), Toast.LENGTH_SHORT)
                        .show();
                return;
            }
        }

        if (noGrantedList.size() > 0) {
            ActivityCompat.requestPermissions(activity, noGrantedList.toArray(new String[noGrantedList.size()]), requestCode);
        } else {
            permissionGrant.onPermissionGranted(requestCode);
        }
    }


    public static void requestPermissionResult(Activity activity, int reqeustCode, String[] permissions, int[] grantResults, PermissionGrant permissionGrant) {

        if (activity == null) {
            return;
        }

        Map<String, Integer> perms = new HashMap<>();

        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            perms.put(permissions[i], grantResults[i]);
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                notGranted.add(permissions[i]);
            }
        }

        if (notGranted.size() == 0) {
            permissionGrant.onPermissionGranted(reqeustCode);
        } else {
            String name = getPermissonName(permissions,activity);
            showDialog(activity, activity.getString(R.string.you_need_to_open_it) + name + activity.getString(R.string.permission_to_use_this_feature), reqeustCode, notGranted.toArray(new String[notGranted.size()]), permissionGrant, false);
        }
    }



    private static String getPermissonName(String[] permissions, Activity activity) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < permissions.length; i++) {
            if (permissions[i].equals(Manifest.permission.RECORD_AUDIO) || permissions[i].equals(Manifest.permission_group.MICROPHONE)) {
                buffer.append(activity.getString(R.string.the_microphone));
            }
            if (permissions[i].equals(Manifest.permission.GET_ACCOUNTS) || permissions[i].equals(Manifest.permission_group.CONTACTS)) {
                buffer.append(activity.getString(R.string.the_address_book));
            }
            if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE) || permissions[i].equals(Manifest.permission_group.PHONE)) {
                buffer.append(activity.getString(R.string.the_phone));
            }
            if (permissions[i].equals(Manifest.permission.CALL_PHONE)) {
                buffer.append(activity.getString(R.string.dial));
            }
            if (permissions[i].equals(Manifest.permission.CAMERA) || permissions[i].equals(Manifest.permission_group.CAMERA)) {
                buffer.append(activity.getString(R.string.the_camera));
            }
            if (permissions[i].contains(Manifest.permission.ACCESS_FINE_LOCATION) || permissions[i].contains(Manifest.permission.ACCESS_FINE_LOCATION) || permissions[i].equals(Manifest.permission_group.LOCATION)) {
                buffer.append(activity.getString(R.string.the_location_information));
            }
            if (permissions[i].contains(Manifest.permission.READ_EXTERNAL_STORAGE) || permissions[i].contains(Manifest.permission.WRITE_EXTERNAL_STORAGE) || permissions[i].equals(Manifest.permission_group.STORAGE)) {
                buffer.append(activity.getString(R.string.storage));
            }
        }
        String messageStr = buffer.toString();
        if (messageStr.isEmpty()) {
            return "";
        }
        return messageStr.substring(0, buffer.toString().length() - 1);
    }

    private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
       try {

        if (dialog == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                dialog = new AlertDialog.Builder(GlobeContext.getContext(), android.R.style.Theme_Material_Light_Dialog)
                        .setMessage(message)
                        .setPositiveButton(context.getString(R.string.confirm), okListener)
                        .setNegativeButton(context.getString(R.string.cancle), cancelListener)
                        .create();
            } else {
                dialog = new AlertDialog.Builder(GlobeContext.getContext())
                        .setMessage(message)
                        .setPositiveButton(context.getString(R.string.confirm), okListener)
                        .setNegativeButton(context.getString(R.string.cancle), cancelListener)
                        .create();
            }

        }
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
       }catch (Exception e){
           ToastUtils.show(message);
           Intent intent = new Intent();
           intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
           Uri uri = Uri.fromParts("package", context.getPackageName(), null);
           intent.setData(uri);
           context.startActivity(intent);
       }


    }


    private static void showDialog(final Activity activity, String message, final int reqeustCode, final String[] requestPermissions, final PermissionGrant permissionGrant, final boolean neddFinsish) {

        showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                boolean isTip = ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermissions[0]);
                if (isTip) {
                    requestPermissions(activity, reqeustCode, requestPermissions, permissionGrant);
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                    intent.setData(uri);
                    activity.startActivity(intent);
                    if (neddFinsish) {
                        activity.finish();
                    }
                }

                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (neddFinsish) {
                    activity.finish();
                }

                dialog.dismiss();
            }
        });
    }


}